{% extends "admin/base.html" %}

{% block title %}评论管理{% endblock %}

{% block content %}
<div class="bg-white rounded-t-xl shadow-sm overflow-hidden m-0">
    <!-- 页面头部 -->
    <div class="px-8 py-6 border-b border-gray-200 flex justify-between items-center flex-wrap gap-4">
        <h1 class="m-0 text-slate-700 text-xl font-semibold flex items-center gap-2">
            <i class="fas fa-comments"></i> 评论管理
        </h1>
        <div class="flex gap-4 items-center">
            <button class="btn-batch-approve" id="btn-batch-approve"><i class="fas fa-check"></i> 批量通过</button>
            <button class="btn-batch-reject" id="btn-batch-reject"><i class="fas fa-times"></i> 批量拒绝</button>
            <button class="btn-batch-delete" id="btn-batch-delete"><i class="fas fa-trash"></i> 批量删除</button>
        </div>
    </div>

    <!-- 筛选和搜索区域 -->
    <div class="comments-filters">
        <div class="filter-group">
            <label for="status-filter">状态筛选</label>
            <select id="status-filter">
                <option value="">全部状态</option>
                <option value="pending">待审核</option>
                <option value="approved">已通过</option>
                <option value="rejected">已拒绝</option>
            </select>
        </div>
        
        <div class="filter-group">
            <label for="search-input">搜索评论</label>
            <input type="text" id="search-input" placeholder="输入评论内容、作者、文章标题...">
        </div>
        
        <button class="btn-filter" onclick="applyFilters()">
            <i class="fas fa-search"></i>
            搜索
        </button>
        
        <button class="btn-reset" onclick="resetFilters()">
            <i class="fas fa-undo"></i>
            重置
        </button>
    </div>

    <!-- 评论表格 -->
    <div class="overflow-x-auto">
        <table class="w-full border-collapse">
            <thead>
                <tr class="bg-gray-50">
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/25"><input type="checkbox" id="check-all"></th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/4">评论内容</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/7">作者</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/4">所属文章</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/10">状态</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/10">时间</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/10">操作</th>
                </tr>
            </thead>
            <tbody id="comments-tbody"></tbody>
        </table>
    </div>
    
</div>

<!-- 分页 -->
<div class="mt-0">
    <div class="bg-white rounded-b-lg shadow-md p-6">
        <div class="flex items-center justify-between">
            <!-- 分页信息 -->
            <div class="text-sm text-gray-600" id="pagination-info">暂无记录</div>
            
            <!-- 分页导航 -->
            <nav class="flex items-center space-x-1" id="pagination-nav"></nav>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
/* 批量操作按钮样式 */
.btn-batch-approve { 
    background-color: #10b981;
    color: white;
    padding: 0.5rem 1rem;
    border: 0;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
    font-weight: 500;
}
.btn-batch-approve:hover { 
    background-color: #059669;
}

.btn-batch-reject { 
    background-color: #f59e0b;
    color: white;
    padding: 0.5rem 1rem;
    border: 0;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
    font-weight: 500;
}
.btn-batch-reject:hover { 
    background-color: #d97706;
}

.btn-batch-delete { 
    background-color: #6b7280;
    color: white;
    padding: 0.5rem 1rem;
    border: 0;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
    font-weight: 500;
}
.btn-batch-delete:hover { 
    background-color: #4b5563;
}

/* 筛选区域样式 */
.comments-filters {
    padding: 1.5rem 2rem;
    background-color: #f9fafb;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    gap: 1rem;
    align-items: center;
    flex-wrap: wrap;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.filter-group label {
    font-size: 0.875rem;
    font-weight: 500;
    color: #6b7280;
}

.filter-group select,
.filter-group input {
    padding: 0.5rem 0.75rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    min-width: 9rem;
    outline: none;
    transition: border-color 0.3s;
}

.filter-group select:focus,
.filter-group input:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.btn-filter {
    background-color: #3b82f6;
    color: white;
    border: 0;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    cursor: pointer;
    font-size: 0.875rem;
    transition: all 0.3s;
    align-self: end;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-filter:hover {
    background-color: #2563eb;
}

.btn-reset {
    background-color: #6b7280;
    color: white;
    border: 0;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    cursor: pointer;
    font-size: 0.875rem;
    transition: all 0.3s;
    align-self: end;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-reset:hover {
    background-color: #4b5563;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
// 评论管理数据
let allComments = [];
let filteredComments = [];
let currentPage = 1;
const perPage = 10;

function formatDate(iso) {
    if (!iso) return '';
    try { return iso.slice(0, 10); } catch { return ''; }
}

async function fetchComments() {
    const res = await fetch('/api/comments?status=');
    const json = await res.json();
    if (!json.success) throw new Error('加载评论失败');
    allComments = json.data.comments || [];
}

function getStatusClass(status) {
    switch(status) {
        case 'pending': return 'bg-yellow-100 text-yellow-800';
        case 'approved': return 'bg-green-100 text-green-800';
        case 'rejected': return 'bg-red-100 text-red-800';
        default: return 'bg-gray-100 text-gray-800';
    }
}

function getStatusText(status) {
    switch(status) {
        case 'pending': return '待审核';
        case 'approved': return '已通过';
        case 'rejected': return '已拒绝';
        default: return status;
    }
}

function applyFilters() {
    const statusFilter = document.getElementById('status-filter').value;
    const searchInput = (document.getElementById('search-input').value || '').trim().toLowerCase();
    
    filteredComments = allComments.filter(comment => {
        const statusMatch = !statusFilter || comment.status === statusFilter;
        const searchMatch = !searchInput || 
            (comment.content || '').toLowerCase().includes(searchInput) ||
            (comment.author_name || '').toLowerCase().includes(searchInput) ||
            (comment.post_title || '').toLowerCase().includes(searchInput);
        return statusMatch && searchMatch;
    });
    
    currentPage = 1;
    renderTable();
    renderPagination();
}

function resetFilters() {
    document.getElementById('status-filter').value = '';
    document.getElementById('search-input').value = '';
    applyFilters();
}

function renderTable() {
    const tbody = document.getElementById('comments-tbody');
    tbody.innerHTML = '';
    const start = (currentPage - 1) * perPage;
    const pageItems = filteredComments.slice(start, start + perPage);
    
    if (pageItems.length === 0) {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td colspan="7" class="text-center py-12 text-gray-500">
            <i class="fas fa-comments text-4xl mb-2"></i>
            <h3 class="m-1 text-lg font-medium text-slate-700">暂无评论</h3>
            <p class="m-0">当有评论时，你可以在这里进行审核与管理。</p>
        </td>`;
        tbody.appendChild(tr);
        return;
    }
    
    for (const comment of pageItems) {
        const tr = document.createElement('tr');
        tr.setAttribute('data-id', comment.id);
        tr.setAttribute('data-status', comment.status);
        tr.className = 'hover:bg-gray-50';
        tr.innerHTML = `
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                <input type="checkbox" class="row-check">
            </td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle" title="${comment.content}">
                <div class="mb-1 leading-relaxed">${comment.content}</div>
                <div class="mt-1">
                    <small class="text-gray-500 text-xs">${comment.author_email}</small>
                </div>
            </td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">${comment.author_name}</td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">${comment.post_title}</td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                <span class="px-3 py-1 rounded-full text-xs font-medium uppercase tracking-wider ${getStatusClass(comment.status)}">
                    ${getStatusText(comment.status)}
                </span>
            </td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">${formatDate(comment.created_at)}</td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                <div class="flex gap-2">
                    <button class="p-2 border-0 rounded cursor-pointer transition-all duration-200 text-sm w-8 h-8 inline-flex items-center justify-center bg-green-100 text-green-600 hover:bg-green-200" onclick="approveComment(${comment.id})" title="通过">
                        <i class="fas fa-check"></i>
                    </button>
                    <button class="p-2 border-0 rounded cursor-pointer transition-all duration-200 text-sm w-8 h-8 inline-flex items-center justify-center bg-amber-100 text-amber-600 hover:bg-amber-200" onclick="rejectComment(${comment.id})" title="拒绝">
                        <i class="fas fa-times"></i>
                    </button>
                    <button class="p-2 border-0 rounded cursor-pointer transition-all duration-200 text-sm w-8 h-8 inline-flex items-center justify-center bg-red-100 text-red-600 hover:bg-red-200" onclick="deleteComment(${comment.id})" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>`;
        tbody.appendChild(tr);
    }
}

function renderPagination() {
    const info = document.getElementById('pagination-info');
    const nav = document.getElementById('pagination-nav');
    nav.innerHTML = '';
    const total = filteredComments.length;
    if (total === 0) { info.textContent = '暂无记录'; return; }
    const start = (currentPage - 1) * perPage + 1;
    const end = Math.min(currentPage * perPage, total);
    info.textContent = `显示第 ${start} - ${end} 条，共 ${total} 条记录`;
    const pages = Math.ceil(total / perPage);
    const mkBtn = (html, disabled, onClick) => {
        const el = document.createElement(disabled ? 'span' : 'a');
        el.className = disabled ? 'px-3 py-2 text-gray-300 cursor-not-allowed' : 'px-3 py-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors';
        el.innerHTML = html;
        if (!disabled) el.addEventListener('click', onClick);
        return el;
    };
    nav.appendChild(mkBtn('<i class="fas fa-angle-double-left"></i>', currentPage === 1, () => { currentPage = 1; renderTable(); renderPagination(); }));
    nav.appendChild(mkBtn('<i class="fas fa-chevron-left"></i>', currentPage === 1, () => { currentPage--; renderTable(); renderPagination(); }));
    for (let p = 1; p <= pages; p++) {
        if (p === currentPage) {
            const span = document.createElement('span');
            span.className = 'px-3 py-2 bg-blue-600 text-white rounded-lg font-medium';
            span.textContent = String(p);
            nav.appendChild(span);
        } else {
            const a = document.createElement('a');
            a.className = 'px-3 py-2 text-gray-700 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors';
            a.textContent = String(p);
            a.addEventListener('click', () => { currentPage = p; renderTable(); renderPagination(); });
            nav.appendChild(a);
        }
    }
    nav.appendChild(mkBtn('<i class="fas fa-chevron-right"></i>', currentPage === pages, () => { currentPage++; renderTable(); renderPagination(); }));
    nav.appendChild(mkBtn('<i class="fas fa-angle-double-right"></i>', currentPage === pages, () => { currentPage = pages; renderTable(); renderPagination(); }));
}

// 批量选择
document.addEventListener('change', function(e) {
    if (e.target && e.target.id === 'check-all') {
        const checked = e.target.checked;
        document.querySelectorAll('#comments-tbody .row-check').forEach(cb => cb.checked = checked);
    }
});

// 评论操作函数
async function approveComment(id) {
    Utils.confirm.show('确定要通过这条评论吗？', async function() {
        try {
            const res = await fetch(`/api/comments/${id}/approve`, { method: 'POST', headers: { 'Content-Type': 'application/json' } });
            const json = await res.json();
            if (json.success) {
                Utils.notification.show('评论已通过', 'success');
                await refreshData();
            } else {
                Utils.notification.show(json.message || '操作失败', 'error');
            }
        } catch (e) {
            Utils.notification.show('操作失败，请稍后重试', 'error');
        }
    });
}

async function rejectComment(id) {
    Utils.confirm.show('确定要拒绝这条评论吗？', async function() {
        try {
            const res = await fetch(`/api/comments/${id}/reject`, { method: 'POST', headers: { 'Content-Type': 'application/json' } });
            const json = await res.json();
            if (json.success) {
                Utils.notification.show('评论已拒绝', 'warning');
                await refreshData();
            } else {
                Utils.notification.show(json.message || '操作失败', 'error');
            }
        } catch (e) {
            Utils.notification.show('操作失败，请稍后重试', 'error');
        }
    });
}

async function deleteComment(id) {
    Utils.confirm.show('确定要删除这条评论吗？删除后无法恢复！', async function() {
        try {
            const res = await fetch(`/api/comments/${id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' } });
            const json = await res.json();
            if (json.success) {
                Utils.notification.show('评论已删除', 'error');
                await refreshData();
            } else {
                Utils.notification.show(json.message || '删除失败', 'error');
            }
        } catch (e) {
            Utils.notification.show('删除失败，请稍后重试', 'error');
        }
    });
}

// 批量操作
document.getElementById('btn-batch-approve').addEventListener('click', async function() {
    const checkedRows = document.querySelectorAll('#comments-tbody .row-check:checked');
    if (checkedRows.length === 0) {
        Utils.notification.show('请先选择要操作的评论', 'warning');
        return;
    }
    Utils.confirm.show(`确定要通过选中的 ${checkedRows.length} 条评论吗？`, async function() {
        try {
            const ids = Array.from(checkedRows).map(cb => cb.closest('tr').getAttribute('data-id'));
            const res = await fetch('/api/comments/batch-approve', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ids })
            });
            const json = await res.json();
            if (json.success) {
                Utils.notification.show(`已通过 ${checkedRows.length} 条评论`, 'success');
                await refreshData();
            } else {
                Utils.notification.show(json.message || '批量操作失败', 'error');
            }
        } catch (e) {
            Utils.notification.show('批量操作失败，请稍后重试', 'error');
        }
    });
});

document.getElementById('btn-batch-reject').addEventListener('click', async function() {
    const checkedRows = document.querySelectorAll('#comments-tbody .row-check:checked');
    if (checkedRows.length === 0) {
        Utils.notification.show('请先选择要操作的评论', 'warning');
        return;
    }
    Utils.confirm.show(`确定要拒绝选中的 ${checkedRows.length} 条评论吗？`, async function() {
        try {
            const ids = Array.from(checkedRows).map(cb => cb.closest('tr').getAttribute('data-id'));
            const res = await fetch('/api/comments/batch-reject', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ids })
            });
            const json = await res.json();
            if (json.success) {
                Utils.notification.show(`已拒绝 ${checkedRows.length} 条评论`, 'warning');
                await refreshData();
            } else {
                Utils.notification.show(json.message || '批量操作失败', 'error');
            }
        } catch (e) {
            Utils.notification.show('批量操作失败，请稍后重试', 'error');
        }
    });
});

document.getElementById('btn-batch-delete').addEventListener('click', async function() {
    const checkedRows = document.querySelectorAll('#comments-tbody .row-check:checked');
    if (checkedRows.length === 0) {
        Utils.notification.show('请先选择要操作的评论', 'warning');
        return;
    }
    Utils.confirm.show(`确定要删除选中的 ${checkedRows.length} 条评论吗？删除后无法恢复！`, async function() {
        try {
            const ids = Array.from(checkedRows).map(cb => cb.closest('tr').getAttribute('data-id'));
            const res = await fetch('/api/comments/batch-delete', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ids })
            });
            const json = await res.json();
            if (json.success) {
                Utils.notification.show(`已删除 ${checkedRows.length} 条评论`, 'error');
                await refreshData();
            } else {
                Utils.notification.show(json.message || '批量操作失败', 'error');
            }
        } catch (e) {
            Utils.notification.show('批量操作失败，请稍后重试', 'error');
        }
    });
});

async function refreshData() {
    await fetchComments();
    applyFilters();
}

document.addEventListener('DOMContentLoaded', async () => {
    try { await refreshData(); } catch (e) { Utils.notification.show('评论加载失败', 'error'); }
});
</script>
{% endblock %}


